import 'dart:convert';
import 'package:get/get.dart';
import 'package:guochaoapp/model/user_entity.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:guochaoapp/common/constant/data_key.dart';

class UserService extends GetxService {

  int dealerId = 1;

  UserEntity _userInfo;

  //用户信息
  UserEntity get userInfo => _userInfo;
  //用户登陆状态
  get isLogin => (_userInfo == null) ? false : true;

  UserService() {
    readUserInfo();
  }

//获取用户数据
  Future readUserInfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    final jsonStr = pref.getString(DataKey.userInfo);
    // print(jsonStr);
    if (jsonStr != null && jsonStr.length > 0) {
      Map json = jsonDecode(jsonStr);
      final model = UserEntity().fromJson(json);
      //保存model的值
      _userInfo = model;
      return model;
    }
    return null;
  }

  //保存用户数据
  void saveUserInfo(UserEntity data) async {
    //替换userInfo的数据
    _userInfo = data;
    //保存userInfo
    SharedPreferences pref= await SharedPreferences.getInstance();
    //将data转换成json
    var str = json.encode(data);
    pref.setString(DataKey.userInfo, str);
  }

  //移除用户数据
  void removeUserInfo() async{
    //清空userInfo
    _userInfo = null;
    //移除已存数据
    SharedPreferences pref= await SharedPreferences.getInstance();
    pref.remove(DataKey.userInfo);
  }
}